package com.seven.good.listener;

import com.seven.good.client.PayClient;
import com.seven.good.enums.GoodStateEnum;
import com.seven.good.pojo.BidRecord;
import com.seven.good.service.AuctionService;
import com.seven.good.service.OrdersService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    AuctionService auctionService;

    @Autowired
    PayClient payClient;

    @Autowired
    OrdersService ordersService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {

        try {
            String key = message.toString();
            int gid = 0;
            gid = Integer.parseInt(key);
            System.out.println("---->"+message.toString()+"商品竞拍结束，核算时间");
            List<BidRecord> records = auctionService.listRecordListById(gid);
            if(records==null){
                // 没人拍卖
                // 商品流拍
                // 通知消息（流拍）,通知发布人
                System.out.println("执行流拍通知发布人消息");
                Map msg = new HashMap();
                msg.put("type",3);
                msg.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                msg.put("gid",gid);
                msg.put("uid",auctionService.getPublisherIdByGid(gid));
                rabbitTemplate.convertAndSend("springboot-exchange","info.auction",msg);
                //System.out.println("商品"+key+"过期");
                // 修改状态
                auctionService.updateGoodState(gid,GoodStateEnum.ABORTIVE.getCode());
            }else{
                // 商品拍卖,商品竞拍时间结束

                // 修改状态
                auctionService.updateGoodState(gid,GoodStateEnum.KNOCK_DOWN.getCode());

                // 更新成交价
                String price = records.get(0).getBidPrice().toString();
                auctionService.updateDealPrice(gid,price);
                // feign....消息，队列

                int uid = records.get(0).getUid();

                // 生成订单，订单号，
                if((int)payClient.createOrder(1,1,price,1).get("result")==1){
                    // 退款，给其他人退保证金
                    payClient.getRefundOrders(1,2,1);
                }

                // 30分钟支付时间,存入redis
                redisTemplate.opsForValue().set("bond"+gid,1,30L, TimeUnit.MINUTES);


                // 商品gid,//人物id,钱pay_amount

                // 通知消息（竞拍成功，竞拍失败）
                Map msg = new HashMap();
                msg.put("type",5);
                msg.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                msg.put("gid",gid);
                for (int i = 1; i < records.size(); i++) {
                    msg.put("uid",records.get(i).getUid());
                    rabbitTemplate.convertAndSend("springboot-exchange","info.auction",msg);
                }
                msg.put("type",4);
                msg.put("uid",uid);
                msg.put("price",price);
                rabbitTemplate.convertAndSend("springboot-exchange","info.auction",msg);

            }
        } catch (NumberFormatException e){
            String str = message.toString();
            if(str.startsWith("bond")){

                Integer gid = Integer.valueOf(str.substring(4));
                // 如果已经付款
                if(ordersService.isPaySuccessful(gid)==1){
                    System.out.println("付款成功");
                }else{
                    // 30分钟后未付款，触发流拍方法
                    payClient.queryDealOrderIfPay(gid);

                    // 通知消息（流拍）
                    System.out.println("执行流拍通知竞拍人消息，");
                    Map msg = new HashMap();
                    msg.put("type",3);
                    msg.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    msg.put("gid",gid);
                    msg.put("uid",auctionService.getNewRecordById(gid).getUid());
                    rabbitTemplate.convertAndSend("springboot-exchange","info.auction",msg);
                }
            }
            System.out.println("spring-session死亡："+message.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
